var $saveButton = $("<div class='BottomBtn'><input type='button' value='保存信息'></div>");
var cache = {};
cache.flag = false;
$(function() {
	loadProvinced();
	loadCustomerType();
	loadIndustryType();
});

function insert() {
	if (cache.flag) {
		artAlert('已经添加完毕');
		return;
	}
	var heads = ["customerName", "sex", "IDNumber", "mp", "tel", "birthday", "email", "fax", "countryId", "address", "zipCode", "industryTypeID", "companyName", "companyDuty", "degree", "marital", "customerType", "password", "memo", "customerGroup"];
	var data = qmsk.collectionData(heads);
	var response = qmsk.asynPost('../customer/insert/customerInfo', data);
	if (response != null) {
		cache.flag = true;
		$("#saveButton").remove();
		var customerId = response.getValue('customerId');
		qmsk.redirectUrl('owner.html', {
			customerId : customerId,
			back : -2
		});
	}
}

function loadIndustryType() {
	$("#industryTypeID").unbind('click');
	$("#industryTypeID").bind('click', function() {
		initSelecter({
			url : '../industryType/find/opt',
			heads : ["Code", "Name"],
			titles : ["编码", "名称"],
			zindex : 500,
			callBack : function(response, row) {
				var id = response.getValue("id", row);
				var name = response.getValue("Name", row);
				qmsk.initSelect({
					datas : [[id, name]],
					id : "industryTypeID"
				});
			}
		});
	});
}

/**
 * 加载客户类型
 */
function loadCustomerType() {
	qmsk.ansyInitSelect({
		method : 'GET',
		url : '../custType/find/opt/0/99',
		id : "customerType",
		heads : ["id", "name"]
	});
}

//加载省份
function loadProvinced() {
	var provinceId = "provinceId";
	$("#" + provinceId).unbind('change');
	$("#" + provinceId).bind('change', function() {
		loadCity();
		$("#countryId").empty().attr('disabled', 'disabled');
	});
	qmsk.ansyInitSelect({
		id : provinceId,
		url : '../location/province',
		heads : ['code', 'name'],
		defaults : {
			key : '选择省'
		}
	});
}

/**
 * 选择好省后加载市
 */
function loadCity() {
	var cityId = "cityId";
	$("#" + cityId).unbind('change');
	$("#" + cityId).bind('change', loadCountry);
	var code = $("#provinceId").val();
	if (code !== "选择省" && qmsk.isNotEmpty(code)) {
		$("#" + cityId).removeAttr('disabled');
		qmsk.ansyInitSelect({
			id : 'cityId',
			url : '../location/city/' + code,
			heads : ['code', 'name'],
			defaults : {
				key : '选择市'
			}
		});
	} else {
		$("#" + cityId).empty().attr('disabled', 'disabled');
	}
}

/**
 * 选择号市后 加载区县
 */
function loadCountry() {
	var countryId = "countryId";
	$("#" + countryId).removeAttr('disabled');
	var code = $("#cityId").val();
	if (qmsk.isNotEmpty(code) && code != '选择市') {
		qmsk.ansyInitSelect({
			id : countryId,
			url : '../location/countries/' + code,
			heads : ['code', 'name']
		});
	} else {
		$("#" + countryId).empty().attr('disabled', 'disabled');
	}
}